/****************************************************
 *javascript KXBASE 前端开发框架
 *@desc 提供常用的表单验证、数据格式转换 权限验证和控制组件css的功能等等
 *      KXBASE命名空间下定义了许多常用函数
 *@data 2012年9月11日13:11:22
*******************************************************/

/**
 * 判断是否存在KXBASE命名空间 不存在就创建一个
 */
if(typeof KXBASE == "undefined" ||!KXBASE) {
    var KXBASE = {};
}


/**
 * 创建一个命名空间 KXBASE
 * @namespace KXBASE
 */
KXBASE.namespace = function() {
    var a=arguments, o=null, i, j, d;
    for (i=0; i<a.length; i=i+1) {
        d=a[i].split(".");
        o=KXBASE;

        for (j=(d[0] == "KXBASE") ? 1 : 0; j<d.length; j=j+1) {
            o[d[j]]=o[d[j]] || {};
            o=o[d[j]];
        }
    }
    return o;
};



/**
 * 对方法的操作，解决内存泄露问题
 * @namespace KXBASE.fn
 */
KXBASE.fn=KXBASE.fn ||{};



/**
 * 这是一个空函数，用于需要排除函数作用域链干扰的情况.
 * @return {Function} 一个空函数
 */
KXBASE.fn.blank = function () {};


var $b=KXBASE.fn;

/*********************************************************
 * 数据格式验证函数定义区
***********************************************************/
KXBASE.fn.isEmpty=function(something){
return (something=="undefined"||something==null||something==""||something==false);
}

KXBASE.fn.isNotEmpty=function(something){
return ((something!=null&&something!="undefined"&&something!="")||something==true);
}

/**
*删除最后一个字符
*/
function deleteLastChar(str,c){
	var reg=new RegExp(c+"([^"+c+"]*?)$");
	return str.replace(reg,function(w){if(w.length>1){return w.substring(1);}else{return "";}});
}

var interval;//计时器


//常用表单验证封装
String.prototype.trim=function(){return this.replace(/(^\s*)|(\s*$)/g, "");}


var g = function (id) {
	return "string" == typeof id ? document.getElementById(id) : id;
};
//摇摆摇摆摇摆起来
jQuery.fn.shake = function(intShakes /*Amount of shakes*/, intDistance /*Shake distance*/, intDuration /*Time duration*/) {
	this.each(function() {
		var jqNode = $(this);
		jqNode.css({position: 'relative'});
		for (var x=1; x<=intShakes; x++) {
			jqNode.animate({ left: (intDistance * -1) },(((intDuration / intShakes) / 4)))
			.animate({ left: intDistance },((intDuration/intShakes)/2))
			.animate({ left: 0 },(((intDuration/intShakes)/4)));
		}
	});
	return this;
}

//检查form表单中的input textarea select
var checkInput=function(optform){
	var error=true;
	$("input,textarea,select",optform).each(function(){
		if(!error){
			return error;
		}
		var input=$(this);
		if(typeof(input.attr("check"))!="undefined"){
			var flag = checktype(input);
			if (!flag) {
				input.css("border","dashed 1px red").css("background","#D3E6B6");
				input.shake(2,10,400);
				input.focus();
				error=false;
				return;
			}
			error=true;
			input.css("border","solid 1px #7F9DB9").css("background","#FFFFFF");
		}
	});
	return error;

}

//检查给定一个input textarea select的值
function checktype(input) {
	var type=input.attr("check"),
	 value=input.val(),
	 mytips=input.attr("tips"),
	  show=input.attr("show"),
	  notNull=input.attr("notNull");
	if (show != null) {
			g(show).innerHTML = "";
	}
		//检测是否为空
			if (value == null || value == "") {
			//检查配置是否需要进行非空检测
							if(notNull==null||notNull==true||notNull=="true"){
									if(mytips!=null){
										if (show == null) {
											alert(mytips);
										} else {
											g(show).innerHTML = mytips;
										}
									}
							return false;
							}else{
							return true;
							}
			}else{
				value=value.trim();
			}
	return checkTypes(type,value,mytips,show,notNull);

}
//检测数据类型
function checkTypes(type,value,mytips,show,notNull){
	//验证多个的时候
	var types=type.split("&");
	var checkFlag=true;
	var error=1;
	var success=2;
	var canNotCheck=3;
	for(var i=0;i<types.length;i++){
		var type=types[i];
		var checkResult=checkSelf(type,value,mytips,show,notNull);
		if(checkResult!=canNotCheck){//判断能否处理 如果处理了 成功了继续下一个type 失败了则直接整个结束
			if(checkResult==success){
				continue;
			}else{
				checkFlag=false;
				break;
			}
		}
		
		//如果上面不能处理 则进入比较处理
		checkResult=checkCompare(type,value,mytips,show,notNull);
		if(checkResult!=canNotCheck){//判断能否处理 如果处理了 成功了继续下一个type 失败了则直接整个结束
			if(checkResult==success){
				continue;
			}else{
				checkFlag=false;
				break;
			}
		}
		
		
	}
	return checkFlag;
}

//检测比较
function checkCompare(type,value,mytips,show,notNull){
	var error=1;
	var success=2;
	var canNotCheck=3;
	var selfValue=getRealTypeValue(value);
	var compareValue=getCompareValue(type);
	if(type.indexOf(">=")!=-1){
		if(selfValue>=compareValue){
			return success;
		}
		showMyTipsIfNeed(mytips,show);
		return error;
	}else if(type.indexOf("<=")!=-1){
		if(selfValue<=compareValue){
			return success;
		}
		showMyTipsIfNeed(mytips,show);
		return error;
	}else if(type.indexOf(">")!=-1){
		if(selfValue>compareValue){
			return success;
		}
		showMyTipsIfNeed(mytips,show);
		return error;
	}else if(type.indexOf("<")!=-1){
		if(selfValue<compareValue){
			return success;
		}
		showMyTipsIfNeed(mytips,show);
		return error;
	}else if(type.indexOf("!=")!=-1){
		if(selfValue!=compareValue){
			return success;
		}
		showMyTipsIfNeed(mytips,show);
		return error;
	}else if(type.indexOf("==")!=-1){
		if(selfValue==compareValue){
			return success;
		}
		showMyTipsIfNeed(mytips,show);
		return error;
	}

	return canNotCheck;
}
//得到正确类型的值
function getRealTypeValue(value){
	if(!isNaN(value)){
		return Number(value);
	}
	return value;
}
//得到需要比较的值
function getCompareValue(type){
	if(type.indexOf("#")!=-1){
		var cid=type.substring(type.indexOf("#"));
		return getRealTypeValue($(cid).val());
	}else{
		if(type.indexOf("=")!=-1){
			return getRealTypeValue(type.substring(2));
		}else{
			return getRealTypeValue(type.substring(1));
		}
	}
}
//显示提示信息
function showMyTipsIfNeed(mytips,show){
	if(mytips!=null){
				if (show == null) {
					alert(mytips);
				} else {
					g(show).innerHTML = mytips;
				}
				}
}
//验证规则map
var ruleMap=[
	{type:"number",method:function(value){return (!isNaN(value));}},//数字校验
	{type:"pnumber",method:function(value){return (!isNaN(value)&&value*1>0);}},//验证正数
	{type:"int",method:function(value){return TestRgexp(/^-?[0-9]\d*$/, value);}},//整数校验
	{type:"pint",method:function(value){return TestRgexp(/^[0-9]*[1-9][0-9]*$/, value);}},//正整数校验
	{type:"email",method:function(value){return TestRgexp(/\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/, value);}},//Email校验
	{type:"filepath",method:function(value){return TestRgexp(/^([a-zA-Z]){1}:(\\[^\/\\:\*\?\"<>]+)*(\\)?$/, value);}},//URL校验
	{type:"date",method:function(value){return TestRgexp(/^(\d{1,4})(-|\/)(\d{1,2})\2(\d{1,2})$/,value);}}//日期验证
];

//检测自身
function checkSelf(type,value,mytips,show,notNull){
	var error=1;
	var success=2;
	var canNotCheck=3;
	if(type=="string"){
		return success;
	}
	var process=false;
	for(var i=0;i<ruleMap.length;i++){
		if(type==ruleMap[i].type){
			process=true;
			var result=ruleMap[i].method.call(this,value);
			if (!result) {
				showMyTipsIfNeed(mytips,show);
				return error;
			}
		}
	}
	return process?success:canNotCheck;
 
	
}
//调用正则表达式验证
function TestRgexp(re, s) {
	return re.test(s);
}




/********************************************************
 * 定义一些常用的数学计算函数
 *******************************************************/
/**
 * 获得随机数 0~n之间的
 * @param {Object} n
 */
function getRandom(n){return Math.floor(Math.random()*n+1)}


/*********************************************************
 * 一些常用的页面效果使用的变量
***********************************************************/


var windowHeight=0;
var windowWidth=0;
var paddingwidth=0;
//处理固定头
var processScrollPanelWidth = function(){
	if ($(".breadcrumb").length > 0) {
		paddingwidth = 40;
	}
	windowHeight = $(window).height();
	windowWidth = $(window).width();
	KXBASE.fn.processScrollPanel();
	$("div.scrollPanel").css("width", windowWidth - paddingwidth);
	$("div.topDiv").css("width", windowWidth - paddingwidth);
	$("div.submitScrollAction").css("position", "absolute").css("z-index", "3").css("top", windowHeight - 35).css("left", (windowWidth - $(this).width()) / 2);
	$("a.submitScrollAction").each(function(){
		$(this).css("position", "absolute").css("z-index", "3").css("top", windowHeight - 35).css("left", (windowWidth - $(this).width()) / 2);
	});
	$("button.submitScrollAction").each(function(){
		$(this).css("position", "absolute").css("z-index", "3").css("top", windowHeight - 35).css("left", (windowWidth - $(this).width()) / 2);
	});
}

KXBASE.fn.processVariable=function(){
	$(window).resize(processScrollPanelWidth);
	$(window).load(processScrollPanelWidth);
}




/*********************************************************
 * 组件的处理函数 以下处理下拉列表 form表单 button等组件绑定的事件
***********************************************************/


/*********************************************************
 * 分页组件的处理函数 临时不用
***********************************************************/

KXBASE.pageNav = KXBASE.pageNav || {};
KXBASE.pageNav.fn = null;
KXBASE.pageNav.pre = "<<";
KXBASE.pageNav.next = ">>";
KXBASE.pageNav.nav = function (a, b) {
	if (1 >= b) {
		return this.pn = this.p = 1, this.pHtml2(1);
	}
	b < a && (a = b);
	var c = "";
	1 >= a ? a = 1 : (c += this.pHtml(a - 1, b, KXBASE.pageNav.pre), c += this.pHtml(1, b, "1"));
	this.p = a;
	this.pn = b;
	var d = 2, e = 9 > b ? b : 9;
	7 <= a && (c += "<li><a href=\"javascript:void(0)\" onclick=\"void(0)\">...</a></li>", d = a - 4, e = a + 4, e = b < e ? b : e);
	for (; d < a; d++) {
		c += this.pHtml(d, b);
	}
	c += this.pHtml2(a);
	for (d = a + 1; d <= e; d++) {
		c += this.pHtml(d, b);
	}
	e < b && (c = c + "<li><a href=\"javascript:void(0)\" onclick=\"void(0)\">...</a></li>" + this.pHtml(b, b));
	a < b && (c += this.pHtml(a + 1, b, KXBASE.pageNav.next));
	return c;
};
KXBASE.pageNav.pHtml = function (a, b, c) {
	return "<li> <a href=\"javascript:KXBASE.pageNav.go(" + a + "," + b + ");\">" + (c || a) + "</a></li>";
};
KXBASE.pageNav.pHtml2 = function (a) {
	return "<li class=\"active\"><a  href=\"javascript:void(0)\" onclick=\"void(0)\">" + a + "</a></li>"
};
KXBASE.pageNav.go = function (a, b) {
	document.getElementById("pagination").innerHTML = "<ul>"+this.nav(a, b)+"</ul>";
	null != this.fn && this.fn(this.p, this.pn);
};

/*********************************************************
 * 自定义弹出窗口的处理函数
***********************************************************/
KXBASE.fn.baseWin = function(windowIndex, title, url, width, height, btnSetting, operateBtnClick, closeBtnClick, extraBtnClick, modalHideHandler){
	var setting = eval(btnSetting);
	var winrandId = "commonModal" + (windowIndex == 0 ? getRandom(100) : windowIndex);
	var haveBtn = false;
	if (KXBASE.fn.isNotEmpty(setting.closeBtn) || KXBASE.fn.isNotEmpty(setting.extraBtn) || KXBASE.fn.isNotEmpty(setting.operateBtn)) {
		haveBtn = true;
	}
	
	/**
	 * 创建窗口
	 */
	var myWindow = '<div id="' + winrandId + '"  class="commonModal modal hide fade in" style="width:' + width + 'px; margin-left: ' + (0 - width / 2) + 'px;"><div class="modal-header"><button type="button" class="close" id="closeModalBtnSmall" >&times;</button><h3>' + title + '</h3></div><div class="modal-body noscroll" style="height:' + height + 'px;"><iframe id="commonActionIframe"   style="width:100%;height:' + (height -35) + 'px;border:0px;" frameborder="0" src=""></iframe></div><div class="modal-footer">';
	if (KXBASE.fn.isNotEmpty(setting.extraBtn)) {
		myWindow = myWindow + '<a href="#" class="btn btn-primary pull-left" id="extraBtn">' + setting.extraBtn + '</a>';
	}
	if (KXBASE.fn.isNotEmpty(setting.closeBtn)) {
		myWindow = myWindow + '<a href="#" class="btn" id="closeModalBtn">' + setting.closeBtn + '</a>';
	}
	if (KXBASE.fn.isNotEmpty(setting.operateBtn)) {
		myWindow = myWindow + '<a href="#" class="btn btn-primary" id="operateBtn">' + setting.operateBtn + '</a>';
	}
	myWindow = myWindow + '</div></div>';
	$("body").append(myWindow);
	$("#commonActionIframe").attr("src", url);
	/**
	 * 绑定按钮事件
	 */
	if (KXBASE.fn.isNotEmpty(setting.closeBtn)) {
		if (KXBASE.fn.isNotEmpty(closeBtnClick)) {
			$("#closeModalBtn").bind("click", function(){
				closeBtnClick();
			});
			$("#closeModalBtnSmall").bind("click", function(){
				closeBtnClick();
			});
		}
		else {
			$("#closeModalBtn").bind("click", function(){
				$("#" + winrandId).modal("hide");
			});
			$("#closeModalBtnSmall").bind("click", function(){
				$("#" + winrandId).modal("hide");
			});
			
		}
	}
	
	if (KXBASE.fn.isNotEmpty(operateBtnClick)) {
		$("#operateBtn").bind("click", function(){
			operateBtnClick();
		});
	}
	if (KXBASE.fn.isNotEmpty(extraBtnClick)) {
		$("#extraBtn").bind("click", function(){
			extraBtnClick();
		});
	}
	/**
	 * 绑定窗口关闭事件
	 */
	$("#" + winrandId).on("hidden", function(){
		$("#operateBtn").unbind("click");
		$("#extraBtn").unbind("click");
		$("#closeBtn").unbind("click");
		$("#" + winrandId).remove();
	});
	
	/**
	 * 显示窗口
	 */
	$("#" + winrandId).modal({
		backdrop: true,
		keyboard: false
	});
	
	if (KXBASE.fn.isNotEmpty(modalHideHandler)) {
	$("#" + winrandId).on("hide", function(){
		return modalHideHandler();
	});
}
	
	

}

/**
 * 给定窗口的Index 关闭它
 * @param {Object} windowIndex
 */
KXBASE.fn.closeByIndex=function(windowIndex){
	$("#commonModal"+windowIndex).modal("hide");
}
/*********************************************************
 * 自定义弹出消息窗口的处理函数
***********************************************************/
KXBASE.fn.alert = function(msg,sec,width){
	if(KXBASE.fn.isEmpty(width)||KXBASE.fn.isEmpty(height)){
		width=560;
	}
	clearTimeout(interval);
	var confirmWindow ='<div id="alertModal" class="alertModal modal hide fade in" style="z-index:5000;width:' + width + 'px; margin-left: ' + (0 - width / 2) + 'px;"><div class="modal-body"><p><img id="alertImg"  src="assets/imgs/info.png"  class="pull-left" /><span id="alertModalMsg" class="confirmMsg pull-right">' + msg + '</span></p></div></div>';
	$("body").append(confirmWindow);
	
	$("#alertModal").modal({
		backdrop:true,
		keyboard:false
	});
	
	if(sec>0){
		interval = setInterval(closeAlert, sec); 
	}
	
	
	
	
};

var closeAlert=function(){
	clearTimeout(interval);
	$("#alertModal").modal("hide");
};
/*********************************************************
 * 自定义弹出确认窗口的处理函数
***********************************************************/
/**
 * 自定义弹出确认窗口的处理函数
 * @param {Object} title
 * @param {Object} msg
 * @param {Object} width
 * @param {Object} height
 * @param {Object} btnSetting json格式{mode:'ync',yesBtn:'是',noBtn:'否',cancelBtn:'取消'}
 * @param {Object} yesClick
 * @param {Object} noClick
 */
KXBASE.fn.confirm = function(title, msg, width, height, btnSetting, yesClick, noClick){
	var setting = eval(btnSetting);
	var confirmWindow = '';
	
	/**
	 * 创建窗口
	 */
	if (KXBASE.fn.isNotEmpty(setting.mode) && setting.mode == 'ync') {
		confirmWindow = '<div id="confirmModal" class="confirmModal modal hide fade in" style="width:' + width + 'px; margin-left: ' + (0 - width / 2) + 'px;"><div id="confirmHeader" class="modal-header"><button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button><h3>' + title + '</h3></div><div class="modal-body noscroll" style="height:' + height + 'px;"><p><img id="confirmImg" src="assets/imgs/help.png" class="pull-left"/><span id="confirmMsg" class="confirmMsg pull-right">' + msg + '</span></p></div><div id="confirmFooter" class="modal-footer"><a href="#" class="btn btn-primary" id="yesBtn">' + setting.yesBtn + '</a><a href="#" class="btn btn-primary" id="noBtn">' + setting.noBtn + '</a><a href="#" class="btn btn-primary" id="cancelBtn">' + setting.cancelBtn + '</a></div></div>';
	}else if (KXBASE.fn.isNotEmpty(setting.mode) && setting.mode == 'yc'){
		confirmWindow = '<div id="confirmModal" class="confirmModal modal hide fade in" style="width:' + width + 'px; margin-left: ' + (0 - width / 2) + 'px;"><div id="confirmHeader" class="modal-header"><button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button><h3>' + title + '</h3></div><div class="modal-body noscroll" style="height:' + height + 'px;"><p><img id="confirmImg"  src="assets/imgs/help.png"  class="pull-left" /><span id="confirmMsg" class="confirmMsg pull-right">' + msg + '</span></p></div><div id="confirmFooter" class="modal-footer"><a href="#" class="btn btn-primary" id="yesBtn">' + setting.yesBtn + '</a><a href="#" class="btn btn-primary" id="cancelBtn">' + setting.cancelBtn + '</a></div></div>';
	}else if (KXBASE.fn.isNotEmpty(setting.mode) && setting.mode == 'close'){
		confirmWindow = '<div id="confirmModal" class="confirmModal modal hide fade in" style="width:' + width + 'px; margin-left: ' + (0 - width / 2) + 'px;"><div id="confirmHeader" class="modal-header"><button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button><h3>' + title + '</h3></div><div class="modal-body noscroll" style="height:' + height + 'px;"><p><img id="confirmImg"  src="assets/imgs/info.png"  class="pull-left" /><span id="confirmMsg" class="confirmMsg pull-right">' + msg + '</span></p></div><div id="confirmFooter" class="modal-footer"><a href="#" class="btn btn-primary" id="closeBtn">' + setting.closeBtn + '</a></div></div>';
	}
	$("body").append(confirmWindow);
	/**
	 * 绑定按钮事件
	 */
	$("#cancelBtn").bind("click", function(){
		$("#confirmModal").modal("hide");
	});
	$("#closeBtn").bind("click", function(){
		$("#confirmModal").modal("hide");
	});
	$("#yesBtn").bind("click", function(){
		yesClick();
	});
	if (KXBASE.fn.isNotEmpty(noClick)) {
	$("#noBtn").bind("click", function(){
		noClick();
	});
	}
	/**
	 * 绑定窗口关闭事件
	 */
	$("#confirmModal").on("hide",function(){
		$("#closeBtn").unbind("click");
		$("#yesBtn").unbind("click");
		$("#cancelBtn").unbind("click");
		$("#noBtn").unbind("click");
		$("#confirmModal").remove();
		clearTimeout(interval);
	});
	
	/**
	 * 显示窗口
	 */
	$("#confirmModal").modal({
		backdrop:true,
		keyboard:false
	});
	
	

}
/**
 * 关闭确认框
 * @param {Object} beforeFun 关闭前干什么
 * @param {Object} appendFun 关闭后干什么
 */
function closeConfirmModal(beforeFun,appendFun){
	if(KXBASE.fn.isNotEmpty(beforeFun)){
		beforeFun();
	}
	$("#confirmModal").modal("hide");
	if(KXBASE.fn.isNotEmpty(appendFun)){
		appendFun();
	}
	clearTimeout(interval);
}
/**
 * 确认框出现滚动条
 */
function confirmWaitting(doWhat){
	$("#confirmHeader").hide();
	$("#confirmFooter").hide();
	$("#confirmMsg").html("操作执行中... <br/><img src=\"assets/imgs/waitting.gif\" />");
	if (KXBASE.fn.isNotEmpty(doWhat)) {
		doWhat();
	}
}
/**
 * 确认框显示信息
 */
function confirmShowMsg(msg,sec){
	 clearTimeout(interval);
	$("#confirmHeader").hide();
	$("#confirmFooter").hide();
	$("#confirmImg").attr("src","assets/imgs/info.png");
	$("#confirmMsg").html(msg);
	if(sec>0){
	interval = setInterval(closeConfirmModal, sec); 
	}
}

/***********************************
 * 封装弹出的进度条和弹出的信息框
 *************************************/
var waittingOver=false;
var zindex=0;
function waitting(backdrop,msg){
	$("div.waittingModal").remove();
	$("div.modal-backdrop[z-index=4000]").remove();
	waittingOver=false;
	if(KXBASE.fn.isNotEmpty(backdrop)){
		backdrop=true;
	}else{
		backdrop=false;
	}
	if (KXBASE.fn.isEmpty(msg)) {
		msg="操作正在执行，请勿执行其它操作，稍等片刻...";
	}
	var waittingWindow='<div id="waittingModal" class="waittingModal modal hide fade in" style="z-index:5000"><div class="modal-body noscroll text-align-center" ><p><img id="waittingImg"  src="assets/imgs/waitting.gif"  /></p><p><span id="waittingMsg" class="waittingMsg">'+msg+'</span></p></div></div>';
	$("body").append(waittingWindow);
		/**
	 * 显示窗口
	 */
	$("#waittingModal").modal({
		backdrop:backdrop,
		keyboard:false
	});
	$("div.modal-backdrop").last().css("z-index",4000);
	$("#waittingModal").on("hide",function(){return waittingOver;});
}

function closeWaitting(){
	closeWaittingNow();
	
}
function closeWaittingNow(){
	clearTimeout(interval);
	waittingOver=true;
	$(".waittingModal").modal("hide");
	
}


/*********************************************************
 * 各种下拉列表的处理函数
***********************************************************/

/**
 *普通下拉列表的选择处理
 *@param selectedItem              选中的选项object
 *@param selectedValueComponentId  指定的要填写选中项目的值的控件、组件的ID 
 *                                 默认是关联的隐藏域 如果没有默认的可以指定任何一个可以赋值value属性的组件的ID 例如input的ID
 *@param selectedTextComponentId   指定的要填写选中项目的文本的控件、组件的ID
 *                                 此参数关联第二个参数，如果第二个参数不填写或者填写不正确 则此参数无用
 */
KXBASE.fn.dropdownSelectOne=function(selectedItem,selectedValueComponentId,selectedTextComponentId){
	var selectText=selectedItem.text();
	var dropdownhtml=selectText+"<b class='caret'></b>";
	var ulId=selectedItem.parent().parent().attr("id");
	var dropdownId=ulId+"_content";
	$("#"+dropdownId).html(dropdownhtml);
	//如果自己指定了要赋值选中Value的组件
	if(KXBASE.fn.isEmpty(selectedValueComponentId)){
		var hiddenInputId=ulId+"_hidden";
		$("#"+hiddenInputId).val(selectedItem.attr("value"));
	}else{
		$("#"+selectedValueComponentId).val(selectedItem.attr("value"));
		//如果自己指定了要赋值选中的text的组件
		if(KXBASE.fn.isEmpty(selectedValueComponentId)){
			$("#"+selectedTextComponentId).val(selectText);
		}
		}
}




/*********************************************************
 * 框架的主要结构部分 以下是页面加载后主要处理函数区域
***********************************************************/

/**
 * 处理隔行变色 只能框架本身调用
 */
KXBASE.fn.processTableColor=function(){
if($(".tablecolor").length>0){
		$(".tablecolor").each(function(i){
				$(this).find("tr:even").addClass("alt");
		});
	
	}

}
/**
 * 处理滚动panel
 */
KXBASE.fn.processScrollPanel=function(){
if($("div.scrollPanel").length>0){
		$("div.scrollPanel").each(function(){
			$(this).css("height",windowHeight-$(this).offset().top-35).css("overflow-x","hidden").css("overflow-y","auto");
		});

	}
	

}

/**
 * 处理隔行变色 只能框架本身调用
 */
KXBASE.fn.processSubnavListener=function(){
 // fix sub nav on scroll
    var $win = $(window)
      , $nav = $('.subnav')
      , navTop = $('.subnav').length && $('.subnav').offset().top - 40
      , isFixed = 0

    processScroll()

    $win.on('scroll', processScroll)

    function processScroll() {
      var i, scrollTop = $win.scrollTop()
      if (scrollTop >= navTop && !isFixed) {
        isFixed = 1
        $nav.addClass('subnav-fixed')
      } else if (scrollTop <= navTop && isFixed) {
        isFixed = 0
        $nav.removeClass('subnav-fixed')
      }
    }


}



//处理页面弹出提示工具提示信息事件监听
KXBASE.fn.processTooltipListener=function(){
//处理tooltip提示信息
	var pl="top"
if($.browser.msie){
$("[rel='tooltip']").each(function(i){
	pl=$(this).attr("placement");
	$(this).tooltip({
		animation:true,
		placement:pl=='undefined'?'top':pl,
		selector:false,
		trigger:'hover'
		});
});
}else{
	$("[type!='text'][rel='tooltip']").each(function(i){
		pl=$(this).attr("placement");
		$(this).tooltip({
		animation:true,
		placement:pl=='undefined'?'top':pl,
		selector:false,
		trigger:'hover'
		});
	});
}

}


/**
 * 处理下拉选择对话框的事件监听 只能框架本身调用
 */
KXBASE.fn.processDropdownChooseLayerListener=function(){

//处理所有搜索层对话框中的选择按钮 class中带有choose属性的
$(".choose").on("click",function(){
var chooseBtn=$(this);
var pid=$("#searchDialog",window.parent.document).attr("pid");    
$("#"+pid,window.parent.document).val(chooseBtn.attr("choosedText"));
$("#"+pid+"_hidden",window.parent.document).val(chooseBtn.attr("choosedKey"));
$("#searchframe",window.parent.document).attr("url","");
$("#searchDialog",window.parent.document).hide();
});

//循环所有下拉搜索组件 绑定焦点事件
$(".withSearchDialog").on("focus",function(){
	var input=$(this);
	var pid=input.attr("id");
	var p=input.offset();
	var w=input.attr("dialogWidth");
	var h=input.attr("dialogHeight");
	var url=input.attr("dialogUrl");
	var ih=30;
	//如果已经弹出了下拉选择搜索组件 就判断是不是自己弹出的
	if($(".searchDialog").length>0){
		//如果是自己弹出的组件 就显示（这里是用在焦点再次停靠的时候）如果不是自己的 就隐藏掉
		if(pid==$("#searchDialog").attr("pid")){
			$("#searchDialog").slideDown();
			return;
		}else{
			$("#searchframe").attr("url","");
			$("#searchDialog").hide();
		}
	}else{//如果在本页面一次都没有弹出过 就创建一个新的弹出层 并且加入到当前文档中
	var searchDialog="<div pid=\""+pid+"\" onmouseover=\"$('#searchDialog').attr('intoFrame','into')\"  onmouseout=\"$('#searchDialog').attr('intoFrame','out')\"  intoFrame=\"out\" id=\"searchDialog\" class=\"searchDialog\" align=\"center\" style=\"display: none; z-index: 999; position: absolute;left:"+p.left+"px;top:"+(p.top+ih)+"px; width:"+w+"px; height:"+h+"px; background: #EEEEEE;  border: 1px solid #dddddd;border-collapse: separate;*border-collapse: collapse;-webkit-border-radius: 4px;-moz-border-radius: 4px;border-radius: 4px; padding: 3px;\">"
									+"<a class=\"icon-hand-up pull-left\" style=\"margin-left:5px;\"  href=\"javascript:void(0)\"></a>"
									+"<a class=\"icon-remove pull-right\" title=\"关闭\" href=\"javascript:void(0)\" onclick=\"$('#searchDialog').hide();$('#searchframe').attr('url','');\">X</a>"
									+"<iframe id=\"searchframe\"  frameborder=\"0\" style=\"width:98%;height:"+(h-ih)+"px;\" src=\"\"></iframe></div>";
	$("body").append(searchDialog);
	}
	//再次将新的值赋给弹出的层
	$("#searchDialog").attr("pid",pid);
	var offset_right=Number(p.left)+Number(w);
	if(offset_right>document.body.clientWidth){
		$("#searchDialog").css("left",self.document.body.clientWidth-w-20);
	}else{
		$("#searchDialog").css("left",p.left);
	}
	$("#searchDialog").css("top",p.top+ih);
	$("#searchDialog").css("width",w);
	$("#searchDialog").css("height",h);
	$("#searchframe").css("height",h-ih);
	$("#searchDialog").slideDown();
	$("#searchframe").attr("src",url);
	
});



		

//绑定焦点移除的
$(".withSearchDialog").on("blur",function(){
	if($.browser.msie){
			$(this).tooltip("hide");
		}
			if($("#searchDialog").attr("intoFrame")=="out"){
				$("#searchframe").attr("url","");
				$(".searchDialog").hide();
				}

});

}
/**
 * 处理下拉列表事件监听 只能框架本身调用
 */
KXBASE.fn.processDropdownListener=function(){
$(".dropdown-menu li a").click(function(){
		if($(this).attr("href")=="#"||$(this).attr("href")=="javascript:void(0)"){
			KXBASE.fn.dropdownSelectOne($(this));
		}
	});

}

/**
 * 处理弹出popover事件
 */
KXBASE.fn.processPopoverListener=function(){
$(".popover-btn").popover();
	  $("a[rel=popover]")
      .popover('toggle')
      .bind('click',function(e) {
        e.preventDefault();
		
      })
}

/**
 * 处理分页组件事件监听 只能框架本身调用
 */
KXBASE.fn.processPagerListener=function(){
	var pager=$("#pagination");
	if(KXBASE.fn.isEmpty(pager)||KXBASE.fn.isEmpty(pager.attr("formId"))){
	//alert("没有分页");
	return;
	}
	
	var formId=pager.attr("formId");
	var cp=pager.attr("currentPage");
	var tp=pager.attr("pageTotal");
	var index=0;
	
	 //  p: 当前 
	 //  pn:总数
	KXBASE.pageNav.fn = function(p,pn){
		if(index>0){
		$("#"+formId).find("#currentPage").val(p);
		$("#"+formId).submit();
		}
		index++;
	};
	KXBASE.pageNav.go(Number(cp),Number(tp));
}


/**
 * 根据权限控制显示和隐藏
 */
KXBASE.fn.processComponents=function(){
	//alert("正在处理页面组件的显示和隐藏");
	//处理隔行变色
	KXBASE.fn.processTableColor();
	KXBASE.fn.processScrollPanel();
}

/**
 * 处理绑定事件
 */
KXBASE.fn.processEventBindings=function(){
	//alert("正在处理页面组件的绑定事件");
	//处理下拉列表
	//KXBASE.fn.processDropdownListener();
	//处理popover
	//KXBASE.fn.processPopoverListener();
	//处理下拉选择弹出对话框事件
	KXBASE.fn.processDropdownChooseLayerListener();
	//处理页面弹出提示工具提示信息事件监听
	//KXBASE.fn.processTooltipListener();
	//处理二级导航
	//KXBASE.fn.processSubnavListener();
	
}
/**
 * 页面加载执行事件绑定处理和控制组件根据权限显示和隐藏
 */
$(function(){
	KXBASE.fn.processVariable();
	//根据权限控制显示和隐藏 根据属性判断table是否加上隔行变色等
	KXBASE.fn.processComponents();
	//绑定按钮 下拉列表等组件的事件
	KXBASE.fn.processEventBindings();
	//js校验
	$("form.checkform").on("submit",function(e){
		var pass=checkInput($(this));
		if(!pass){
			closeWaittingNow();
		}
		return pass;
	});
	
});



/**********************************************
 * 固定头的table js实现
 ************************************/
var processOneTableScroll=function(myTable){
			myTable.hide();
			var basetable=myTable.clone();
			basetable.removeClass("baseTable");
			var tableClass=basetable.attr("class");
			var scrollpanel=myTable.parent();
			var scrollpanelPos=scrollpanel.offset();
			var tableHeadBottom=basetable.find("thead").html();
			var swidth=5;
			var margintophead=15;
			if($.browser.msie){
				swidth=5;
			}else if($.browser.mozilla){
				swidth=6;
			}else{
				swidth=1;
			}
			var scrollMode="auto";
			if(myTable.height()>$(window).height()-scrollpanelPos.top-28){
				scrollMode="scroll";
				basetable.find("thead").find("tr").append("<th id=\"scrollth\" style=\"width:"+swidth+"px\"></th>");
			}
			var tableHead=basetable.find("thead").html();
			var tableBody=basetable.find("tbody").html();
			$("<div/>").attr("class","topDiv").css("position","absolute").css("z-index","2").css("overflow","hidden").css("left",scrollpanelPos.left).css("top",scrollpanelPos.top).css("width",scrollpanel.width()).attr("id","topDiv").appendTo(scrollpanel);
			$("<table/>").attr("id","headTable").attr("cellspacing","0").attr("cellpadding","0").attr("border","0").attr("class",tableClass).css("width","100%").html("<thead>"+tableHead+"</thead>").appendTo($("#topDiv"));
			$("#topDiv").css("height",$("#headTable").height());
			var theadHeight=$("#headTable").height();
			margintophead=theadHeight>28?theadHeight-15:theadHeight-9;
			$("<div/>").attr("class","scrollPanel").css("position","absolute").css("z-index","1").css("overflow-x","hidden").css("overflow-y",scrollMode).css("left",scrollpanelPos.left).css("top",scrollpanelPos.top+margintophead).css("width",scrollpanel.width()).attr("id","scrollPanel").appendTo($(scrollpanel));
			$("<table/>").attr("id","bottomTable").attr("class",tableClass).attr("cellspacing","0").attr("cellpadding","0").attr("border","0").css("width","100%").html("<thead id='bottomThead'>"+tableHeadBottom+"</thead><tbody>"+tableBody+"</tbody>").appendTo($("#scrollPanel"));
			$("#bottomThead").find("th").text("");
			myTable.remove();
			$("#bottomTable").resize(function(){
				if($("#scrollPanel").scrollTop()<=0){
					$("#scrollth").remove();
				}
				
			});
			
		}
		
!function($){
	$(function(){
		$("div.baseTableScrollPanel").find("table.baseTable").each(function(){
			processOneTableScroll($(this));
		});
		
		processScrollPanelWidth();
	//判断滚动条滚动处理事件
	if($("div.popover").length>0){
			$("#scrollPanel").scroll(function(){
				$("div.popover").hide();
          });
	}
	
	});
}(window.jQuery);


!function($){
	$(function(){
    // get only (input:text) tags with class data-entry
    textboxes = $("input:text");
    // now we check to see which browser is being used
    if ($.browser.mozilla) {
        $(textboxes).keypress (checkForEnter);
    } else {
        $(textboxes).keydown (checkForEnter);
    }
});

function checkForEnter (event) {
    if (event.keyCode == 13) {
          currentBoxNumber = textboxes.index(this);
        if (textboxes[currentBoxNumber + 1] != null) {
            nextBox = textboxes[currentBoxNumber + 1]
            nextBox.focus();
            nextBox.select();
            event.preventDefault();
            return false;
        }
    }
}

}(window.jQuery);




var refreshPage=function(){
	if($("form[name='form2']").length>0){
		form2.submit();
	}else{
		window.location.reload();
	}
	
}
var nofun=function(){}


var refreshParentWithForm=function(){
	
		$("#closeModalBtn").bind("click", function(){
				form2.submit();
			});
			$("#closeModalBtnSmall").bind("click", function(){
				form2.submit();
			});
			$(".commonModal").bind("hide", function(){
				form2.submit();
			});
}
var refreshParentWithoutForm=function(){
	
		$("#closeModalBtn").bind("click", function(){
				window.location.reload();
			});
			$("#closeModalBtnSmall").bind("click", function(){
				window.location.reload();
			});
			
			$(".commonModal").bind("hide", function(){
				window.location.reload();
			});
}

var refreshParent=function(){
	if($("form[name='form2']").length>0){
		refreshParentWithForm();
	}else{
		refreshParentWithoutForm();
	}
		
}

var pageBack=function(){
	history.go(-1);
}

var modalBack=function(){
	history.go(-1);
}
